<!-- SuperTable的作用域插槽:
	1.表格列的插槽:table + 列名(在配置文件中定义),scope.row中存放每行的数据
	<template #table-handler="scope">
		<el-button 
			v-hasPermission="'receivedproblem:detail'"
			plain size="small" type="success"
			@click="handleButtonClick('detail', scope.row)">详情</el-button>
	</template>
	2.搜索区域的按钮插槽:search-buttons,提供 queryData,resetQueryData,exportExcel,分别可以实现查询,重置,导出excel的功能
	<template #search-buttons="{queryData,resetQueryData}">
		<el-button type="primary" @click="queryData">
			查询
		</el-button>
		<el-button type="warning" @click="resetQueryData">
			重置
		</el-button>
		<el-button type="success" @click="handleButtonClick('add')" v-if="$store.getters.hasPermission('sendoutproblem:add')">
			新增
		</el-button>
	</template>
-->
<template>
	<div class="super-table">
		<div class="content" >
			<display-search
				v-show="showSearch"
				ref="DisplaySearchRef"
				class="super-table-display-search"
				:showSearch="showSearch"
				v-bind="searchConfig"
				:showExportExcel="showExportExcel || searchConfig.showExportExcel"
				:exportExcelLoading="exportExcelLoading"
				v-model="searchFormData"
				@resetQueryData="handleResetBtnClick"
				@queryData="handleQueryBtnClick"
				@exportExcel="exportExcel">
				<template #reWriteButtons="scope">
					<slot name="search-buttons" v-bind="scope.funcs">
					</slot>
				</template>
			</display-search>
			<div class="search-table-distance"></div>
			<display-table
				:listLoading="listLoading"
				element-loading-text="加载中..."
				class="super-table-display-table"
				ref="displayTableRef"
				:showIndexColumn="showIndexColumn" 
				:detailPropList="detailPropList" 
				:detailDataList="detailDataList"
				:rowKey="rowKey"
				:showFooter="showFooter"
				:header_cell_style="header_cell_style"
				:cellStyle="cellStyle"
				:globalMaxTextLine="globalMaxTextLine"
				:getRowStyle="getRowStyle"
				:detailDataConut="detailDataConut"
				:tableMinHeight="tableMinHeight"
				v-model:page="pageInfo">
					<template
						v-for="item in detailPropList"
						:key="item.prop"
						#[item.prop]="scope"
					>
					<!-- 上边如果报错,是编译器报错 -->
					    <!-- 2023 06 07 需要两行显示文字,多余用省略号显示 悬浮后显示弹框 特定场景需要,否则不需要-->
						<el-tooltip
							v-if="item.maxTextLine || globalMaxTextLine"
							placement="top"
							v-model="scope.row.showTooltip"
							:disabled="!scope.row.showTooltip">
								<div 
								@mouseenter="showTips($event,scope.row,item.prop,item.maxTextLine||globalMaxTextLine||1,item.defaultValue)"
								class='myNote'
								:style="{'-webkit-line-clamp': item.maxTextLine||globalMaxTextLine||1,'line-clamp': item.maxTextLine||globalMaxTextLine||1}"
								>
									<slot :name="`table-${item.prop}`" :row="scope.row">
										{{(scope.row&&scope.row[item.prop]) ?? item.defaultValue}}
									</slot>
								</div>
							<template #content>
								<slot :name="`table-${item.prop}-tooltip-content`" :row="scope.row">
									{{(scope.row&&scope.row[item.prop]) ?? item.defaultValue}}
								</slot>
							</template>
						</el-tooltip>
						<slot v-else :name="`table-${item.prop}`" :row="scope.row">
							{{(scope.row&&scope.row[item.prop]) ?? item.defaultValue}}
						</slot>
					</template>
			</display-table>
		</div>
	</div>
</template>
<script setup>
import { ref,toRefs,computed,watch,getCurrentInstance,onMounted,nextTick,defineExpose } from "vue";
import DisplayTable from "./base-ui/DisplayTable.vue";
import DisplaySearch from "./base-ui/DisplaySearch.vue";
import moment from "moment";
const props=defineProps({
	getTableDataFunction:{//数据查询方法
		type:Function,
		require:false,
		default:()=>([])
	},
	detailPropList:{//表格的列以及属性
		type:Array,
		require:true,
		default:[]
	},
	showSearch:{//是否显示搜索区域
		type:Boolean,
		require:false,
		default:()=>true
	},
	showFooter:{//是否显示分页器
		type:Boolean,
		require:false,
		default:()=>true
	},
	showIndexColumn:{//是否显示序号
		type:Boolean,
		require:false,
		default:()=>true
	},
	showExportExcel:{//是否显示导出excel按钮
		type:Boolean,
		require:false,
		default:()=>false
	},
	searchConfig:{//搜索区域的表单配置
		type:Object,
		require:false,
		default:()=>({})
	},
	////////////////////////////////////////以下不用传////////////////////
	doSomeSthingbeforeQueryData:{//在初始化的时候做点什么
		type:Function,
		require:false,
		default:undefined
	},
	initSearchData:{//初始化搜索框的值,界面上也会有显示
		type:Object,
		require:false,
		default:()=>({})
	},
	fixedCondition:{//固定的搜索条件，每次查询数据都会带上
		type:Object,
		require:false,
		default:()=>({})
	},
	tableMinHeight: {//给table的高度设限,默认是占满superTable组件给的空间(除去搜索区域)
      type: String,
      required: false,
      default:'none'
    },
	cellStyle: {
      type: Object,
      default: ()=>({})
    },
	rowKey: {//如果加载树结构的数据,传这个
      type: String,
      required: false,
      default:''
    },
	globalMaxTextLine: {//TABLE的元素文字最多显示几行后,使用省略号
      type: Number,
      required: false,
      default:undefined
    },
});
const {detailPropList,showSearch,searchConfig,tableMinHeight,tableMaxHeight}=toRefs(props);//只读的
const title=ref('数据详情');
const detailDataList = ref([]);//可修改的
const listLoading = ref(false);
const exportExcelLoading = ref(false);
const DisplaySearchRef = ref(null);//可修改的
const detailDataConut = ref(0);//可修改的
const emit=defineEmits(['close']);
const close=()=>{
    emit('close',false);
}
//定义一个对象searchFormData，存储的是search的数据
const searchProps = searchConfig?.searchProps ?? []
const formOriginData = {}
for (const item of searchProps) {
	formOriginData[item.field] = ''
}
const searchFormData = ref(formOriginData)
const displayTableRef = ref(null)
//el-table表头样式
const header_cell_style = {
	// height: '3vh',
	// background: 'rgb(17,43,74)',
	// color: '#38C4FF',
	// 'font-size': '18px',
	// 'text-align': 'center',
	// 'font-weight': 400,
	// 'font-family': 'PingFangSC'
}
//el-table奇数和偶数行样式
const getRowStyle = ({ row, rowIndex }) => {
	// 	if ((rowIndex + 1) % 2 === 0) {
	// 		return "background:rgb(17,43,74);border:none;color:#FFFFFF;height:3vh;";
	// 	} else {
	// 		return "background:#000B1F;border:none;color:#FFFFFF;height:3vh;";
	// 	}
}
//点击了查询按钮逻辑
const handleQueryBtnClick=()=>{
	pageInfo.value.currentPage=1
	getPageData()
};
const showTips = (obj, row,text,maxTextLine=1,defaultText)=>{
	//生成一个span元素,内容是text,挂载到body上,计算他的宽度,计算完后,删除
	let TemporaryTag = document.createElement('span');
	TemporaryTag.innerText = row[text] || defaultText;
	TemporaryTag.className = 'getTextWidth';
	document.querySelector('body').appendChild(TemporaryTag);
	let needWidth = document.querySelector('.getTextWidth').offsetWidth;
	document.querySelector('.getTextWidth').remove();
	//计算cell的宽度度
	const cellWidth = obj.target.offsetWidth
	needWidth <= (maxTextLine * cellWidth) ? row.showTooltip = false : row.showTooltip = true
	if(text=='handler'){//操作栏不显示tooltip了 2023 12 08
		row.showTooltip = false
	}
}
const exportExcel = async()=>{
	exportExcelLoading.value=true
	let currentPageTemp=undefined
	let pageSizeTemp=undefined
	let data = []
	const res = await props.getTableDataFunction(currentPageTemp,pageSizeTemp,{...searchFormData.value,...props.fixedCondition})
	const querysuccess = res?.querysuccess || false
	const totalcount = res?.totalcount || 0
	const datalist = res?.datalist || []
	if(querysuccess){
		data = datalist
	}
	let result = []
	data.forEach(item=>{//顺序要对的上,否则有问题,有时间修复!
		let obj = {}
		detailPropList.value.forEach(el=>{
			let temp = item[el.prop]
			if(el.timeStampFormat){
				temp = formatStampToTime(temp)
			}else if(el.codeMap){
				temp = formatCodeToLabel(temp,el.codeMap)
			}
			if(el.prop!=='handler'){
				obj[el.prop] = temp||''
			}
		})
		result.push(obj)
	})
	let headStr = detailPropList.value.filter(item=>item.prop!=='handler').map(item=>item.label)
	let str =headStr.join(",")+'\n'

	for(let i = 0 ; i < result.length ; i++ ){
		for(let item in result[i]){
			str+=`${result[i][item] + '\t'},`;  
		}
		str+='\n';
	}
	let uri = 'data:application/vnd.ms-excel;charset=utf-8,\ufeff' + encodeURIComponent(str);
	const link = document.createElement("a");
	link.href = uri;
	// 对下载的文件命名
	link.download =  "数据列表.xls";
	document.body.appendChild(link);
	link.click();
	document.body.removeChild(link);
	exportExcelLoading.value=false
	getPageData()
}
//点击了清空按钮逻辑
const handleResetBtnClick=()=>{
	//把表单数据清空
	searchFormData.value = formOriginData;
	//改成第一页
	pageInfo.value.currentPage=1
	//重新查询
	getPageData()
};
//获取数据接口，接口内容由调用该组件的地方写，必须是返回promise的方法
const getPageData = async() =>{
	listLoading.value=true
	const {querysuccess,totalcount,datalist} = await props.getTableDataFunction(pageInfo.value.currentPage,pageInfo.value.pageSize,{...searchFormData.value,...props.fixedCondition})
	if(querysuccess){
		detailDataConut.value = totalcount
		detailDataList.value = datalist
	}
	listLoading.value=false
};
//监听子组件的分页器，如果变化，那么重新查询数据
const pageInfo = ref({ currentPage: 1, pageSize: 15 })
//时间戳转换
const formatStampToTime= (stamp,format="YYYY-MM-DD HH:mm:ss")=>{
	if (stamp == 0 || stamp == null || stamp == "")
		return '未设置';
	return moment(Number(stamp))
		.locale("zh-cn")
		.format(format);
}
//格式转换
const formatCodeToLabel = (title,codemap) => {
	return codemap.find(item=>item.value===title)?.title||title
}
watch(pageInfo, () => getPageData())

onMounted(()=>{
	//1遍历一下searchConfig?.value?.searchProps
	let firstQueryParams = {}
	searchConfig?.value?.searchProps?.forEach(item=>{
		if(item.defaultValue){
			firstQueryParams[item.field] = item.defaultValue
		}
	})

	nextTick(()=>{
		DisplaySearchRef.value.subModelValue = {...DisplaySearchRef.value.subModelValue,...props.initSearchData,...firstQueryParams}
		searchFormData.value = {...searchFormData.value,...props.initSearchData,...firstQueryParams}
		props.doSomeSthingbeforeQueryData && props.doSomeSthingbeforeQueryData(getCurrentInstance())
		getPageData()
	})
})

defineExpose({ getPageData,refresh:getPageData });
</script>
<style scoped>
.tabletext{
    overflow:hidden;
    text-overflow:ellipsis;
    white-space:nowrap;
}
.content{
	width: 100%;
	height:100%;
	display: flex;
	flex-direction: column;
}
.super-table{
	width: 100%;
	height:100%;
	padding:  10px;
}
.super-table-display-search{
	width:100%;
	background-color: white;
    padding-top: 20px;
}
.super-table-display-table{
	flex-grow: 1;
	width:100%;
	overflow: hidden;
	background-color: white;
    padding: 15px 15px 0 15px;
}
/* 弹框上部空白缩小*/
/* 底部分页器居中*/
.super-table-display-table :deep() .footer{
	height: 50px;
	display: flex;
	justify-content: center;
	align-items: center;
}
.myNote{
	text-overflow: -o-ellipsis-lastline;
	overflow: hidden;				
	text-overflow: ellipsis;		
	display: -webkit-box;		
	-webkit-line-clamp: 1;			
	line-clamp: 1;					
	-webkit-box-orient: vertical;	
}
</style>